<?php

class SJB_Admin_Payment_TransactionHistory extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('manage_payments');
		return parent::isAccessible();
	}

	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();
		$errors = array();
		$page = 1;
		if (!empty($_REQUEST['page']))
			$page = intval($_REQUEST['page']);
		$items_per_page = 100;

		/********** A C T I O N S   W I T H   P A Y M E N T S **********/
		$action = SJB_Request::getVar('action_name', SJB_Request::getVar('action', false));
		$payments_sids = SJB_Request::getVar('payments', false);

		if ($action && $payments_sids) {
			$payments_sids = $_REQUEST['payments'];
			$_REQUEST['restore'] = 1;

			if ($action == 'endorse') { // ENDORSE
				foreach ($payments_sids as $payment_sid => $value) {
					$payment_info = SJB_PaymentManager::getPaymentInfoBySID($payment_sid);
					$product_info = !empty($payment_info) ? unserialize($payment_info['product_info']) : array();

					// if current payment completed - skip it!
					if ($payment_info['status'] == 'Completed') {
						$errors[] = 'PAYMENT_IS_NOT_PENDING';
						continue;
					}

					if (isset($product_info['listing_id'])) {
						SJB_ListingManager::activateListingBySID($product_info['listing_id']);
						SJB_PaymentManager::endorsePayment($payment_sid);
						SJB_Statistics::addStatistics('payment', 'activateListing', $payment_sid, false, 0, 0, $payment_info['user_sid'], $payment_info['price']);
					}
					elseif (isset($product_info['listings_ids'])) {
						$listings_ids = array_pop($product_info['listings_ids']);
						foreach ($listings_ids as $listing_id)
							SJB_ListingManager::activateListingBySID($listing_id);
						SJB_PaymentManager::endorsePayment($payment_sid);
						SJB_Statistics::addStatistics('payment', 'activateListing', $payment_sid, false, 0, 0, $payment_info['user_sid'], $payment_info['price']);
					}
					elseif (isset($product_info['products'])) {
						$user_sid = $payment_info['user_sid'];
						foreach ($product_info['products'] as $key => $product) {
							$product = unserialize($product);
							$listingNumber = !empty($product['number_of_listings']) ? $product['number_of_listings'] : null;
							$contract = new SJB_Contract(array('product_sid' => $product['sid'], 'numberOfListings' => $listingNumber, 'is_recurring' => $payment_info['is_recurring']));
							$contract->setUserSID($user_sid);
							$contract->setPrice($product['price']);
							if ($contract->saveInDB()) {
								SJB_ShoppingCart::deleteItemFromCartBySID($product['shoppingCartRecord'], $user_sid);
								$paymentStatus = true;
								if ($product['product_type'] == 'banners' && !empty($product['banner_info'])) {
									$bannersObj = new SJB_Banners();
									$bannerInfo = $product['banner_info'];
									$bannerSID = $bannersObj->addBanner($bannerInfo['title'], $bannerInfo['link'], $bannerInfo['bannerFilePath'], $bannerInfo['sx'], $bannerInfo['sy'], $bannerInfo['type'], 0, $bannerInfo['banner_group_sid'], $bannerInfo, $user_sid, $contract->getID());
									$bannerGroup = $bannersObj->getBannerGroupBySID($bannerInfo['banner_group_sid']);
									SJB_AdminNotifications::sendAdminBannerAddedLetter($user_sid, $bannerGroup);
								}
								if ($contract->isFeaturedProfile())
									SJB_UserManager::makeFeaturedBySID($user_sid);
								if (SJB_UserNotifications::isUserNotifiedOnSubscriptionActivation($user_sid))
									SJB_Notifications::sendSubscriptionActivationLetter($user_sid, $product);
							}
							SJB_Statistics::addStatistics('payment', 'product', $product['sid'], false, 0, 0, $user_sid, $product['price']);
						}
						SJB_PaymentManager::endorsePayment($payment_sid);
					}
					elseif (isset($product_info['featured_listing_id'])) {
						SJB_ListingManager::makeFeaturedBySID($product_info['featured_listing_id']);
						SJB_PaymentManager::endorsePayment($payment_sid);
						SJB_Statistics::addStatistics('payment', 'featuredListing', $payment_sid, false, 0, 0, $payment_info['user_sid'], $payment_info['price']);
					}
					elseif (isset($product_info['priority_listing_id'])) {
						SJB_ListingManager::makePriorityBySID($product_info['priority_listing_id']);
						SJB_PaymentManager::endorsePayment($payment_sid);
						SJB_Statistics::addStatistics('payment', 'priorityListing', $payment_sid, false, 0, 0, $payment_info['user_sid'], $payment_info['price']);
					}
				}
			}
			elseif ($action == 'delete') { // DELETE
				foreach ($payments_sids as $payment_sid => $value)
					$res = SJB_PaymentManager::deletePaymentBySID($payment_sid);
			}
			else {
				unset($_REQUEST['restore']);
			}
		}

		/**********  D E F A U L T   V A L U E S   F O R   S E A R C H  **********/

		$_REQUEST['action'] = 'filter';

		$i18n = SJB_ObjectMother::createI18N();
		if (!isset($_REQUEST['creation_date'])) {
			$_REQUEST['creation_date']['not_less'] = $i18n->getDate(date('Y-m-d', time() - 30 * 24 * 60 * 60));
			$_REQUEST['creation_date']['not_more'] = $i18n->getDate(date('Y-m-d', time() + 24 * 60 * 60));
		}
		else {
			if (!$i18n->isValidDate($_REQUEST['creation_date']['not_less']) && !empty($_REQUEST['creation_date']['not_less']))
				$errors[] = 'INVALID_PERIOD_FROM';
			if (!$i18n->isValidDate($_REQUEST['creation_date']['not_more']) && !empty($_REQUEST['creation_date']['not_more']))
				$errors[] = 'INVALID_PERIOD_TO';
		}

		/************************ S E A R C H   F O R M ***************************/
		$payment = new SJB_Payment();
		$payment->addProperty(array(
				'id' => 'username',
				'type' => 'string',
				'value' => '',
				'is_system' => true,
			)
		);

		$aliases = new SJB_PropertyAliases();
		$aliases->addAlias(array(
				'id' => 'username',
				'real_id' => 'user_sid',
				'transform_function' => 'SJB_UserManager::getUserSIDsLikeUsername',
			)
		);

		$search_form_builder = new SJB_SearchFormBuilder($payment);
		$criteria_saver = new SJB_PaymentCriteriaSaver();

		if (isset($_REQUEST['restore']))
			$_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());

		$criteria = $search_form_builder->extractCriteriaFromRequestData($_REQUEST, $payment);

		$search_form_builder->setCriteria($criteria);
		$search_form_builder->registerTags($tp);

		$tp->display('payment_form.tpl');

		/********************  S E A R C H  ************************/

		$sorting_field = SJB_Request::getVar('sorting_field', 'creation_date');
		$sorting_order = SJB_Request::getVar('sorting_order', 'DESC');
		$inner_join = false;
		if ($sorting_field == 'username')
			$inner_join = array('users' => array('sort_field' => 'username', 'join_field' => 'sid', 'join_field2' => 'user_sid', 'join' => 'LEFT JOIN'));

		$searcher = new SJB_PaymentSearcher(($page - 1) * $items_per_page, $sorting_field, $sorting_order, $inner_join);

		// for dividing the usecase
		// $criteria = SearchFormBuilder::extractCriteriaFromRequestData($_REQUEST, $payment);
		$found_payments = array();
		$found_payments_sids = array();

		if (SJB_Request::getVar('action', '') === 'filter') {
			$found_payments = $searcher->getObjectsByCriteria($criteria, $aliases);
			$criteria_saver->setSession($_REQUEST, $searcher->getFoundObjectSIDs());
		}
		elseif (isset($_REQUEST['restore'])) {
			$found_payments = $criteria_saver->getObjectsFromSession();
		}

		$total_price = 0;

		foreach ($found_payments as $id => $payment) {
			$total_price += $payment->getPropertyValue('price');
			$user_sid = $payment->getPropertyValue('user_sid');
			$username = SJB_UserManager::getUserNameByUserSID($user_sid);

			$payment->addProperty(array(
				'id' => 'sid',
				'type' => 'string',
				'value' => $payment->getSID(),
			));

			$payment->addProperty(array(
				'id' => 'username',
				'type' => 'string',
				'value' => $username,
			));

			$found_payments_sids[$payment->getSID()] = $payment->getSID();
			$found_payments[$id] = $payment;
		}

		/*********************** S O R T I N G **************************/
		$listingsCount = $searcher->getAffectedRows();
		$sorted_found_payments_sids = $found_payments_sids;
		/****************************************************************/

		$pages = array();

		for ($i = $page - 3; $i < $page + 3; $i++) {
			if ($i > 0)
				$pages[] = $i;
			if ($i * $items_per_page > $listingsCount)
				break;
		}

		$totalPages = ceil($listingsCount / $items_per_page);
		if (empty($totalPages))
			$totalPages = 1;

		if (array_search(1, $pages) === false)
			array_unshift($pages, 1);
		if (array_search($totalPages, $pages) === false)
			array_push($pages, $totalPages);

		$tp->assign('currentPage', $page);
		$tp->assign('totalPages', $totalPages);
		$tp->assign('pages', $pages);
		$tp->assign('listingsCount', $listingsCount);

		$form_collection = new SJB_FormCollection($found_payments);
		$form_collection->registerTags($tp);

		$tp->assign('errors', $errors);
		$tp->assign('sorting_field', $sorting_field);
		$tp->assign('sorting_order', $sorting_order);
		$tp->assign('found_payments_sids', $sorted_found_payments_sids);
		$tp->assign('total_price', $total_price);

		$tp->display('payments.tpl');
	}
}
